/*
 * DbHttpUserStore.cpp
 *
 *  Created on: 2018年2月9日
 *      Author: terry
 */

#include "DbHttpUserStore.h"
#include "DbRow.h"
#include "TStringUtil.h"

template <>
bool fromRow(HttpUser& httpUser, db::DbRow& row)
{
    row.get("password", httpUser.password);
    return true;
}



DbHttpUserStore::DbHttpUserStore(std::shared_ptr< db::DbConnectionPool >& dbPool):
	m_dbPool(dbPool)
{
}

DbHttpUserStore::~DbHttpUserStore()
{
}

void DbHttpUserStore::setDb(std::shared_ptr< db::DbConnectionPool >& dbPool)
{
	m_dbPool = dbPool;
}

bool DbHttpUserStore::findUser(const std::string& username, HttpUser& user)
{
	return findLocal(username, user) || findDb(username, user);
}

bool DbHttpUserStore::findDb(const std::string& username, HttpUser& user)
{
	if (!m_dbPool)
	{
		return false;
	}

	db::DbConnection conn(*m_dbPool);
	if (!conn.validate())
	{
		return false;
	}

    std::string sql = comn::StringUtil::format("select user.* from user join user_info on user.id=user_info.id where (user.username='%s' or user.id='%s') and user_info.enabled > 0",
        username.c_str(), username.c_str());

    if (!conn.queryObject(sql, user))
	{
		return false;
	}

	user.username = username;

	return true;
}
